package traveldream.ejb.sessionBean;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import traveldream.ejb.DTO.RegistrationDTO;
import traveldream.ejb.entities.*;
import traveldream.ejb.interfaces.NotFindException;
import traveldream.ejb.interfaces.ProfileEditBeanLocal;

/**
 * Session Bean implementation class ProfileEditBean
 */
@Stateless
public class ProfileEditBean implements ProfileEditBeanLocal {

	@PersistenceContext
	private EntityManager em;
	
    /**
     * Default constructor. 
     */
    public ProfileEditBean() {
        // TODO Auto-generated constructor stub
    }

	@Override
	public RegistrationDTO findUser(String user) throws NotFindException{
		User u = em.find(User.class, user);
    	if(u!=null)
    		return convertToDTO(u);
    	else throw new NotFindException();
	}

	private RegistrationDTO convertToDTO(User u) {
		RegistrationDTO reDTO = new RegistrationDTO();
		reDTO.setAddress(u.getAddress());
		reDTO.setIdUser(u.getIdUser());
		reDTO.setName(u.getName());
		reDTO.setPhone(u.getPhone());
		reDTO.setSurName(u.getSurname());
		return reDTO;
	}

	@Override
	public void save(RegistrationDTO reDTO) {
		User u = new User(reDTO);
		List<Group> groups = new ArrayList<Group>();
		groups.add(Group.USER);
		u.setGroups(groups);
		em.merge(u);
	}

}
